//加载express 
const express = require('express');
//实例路由 
const router = express.Router();
//导入数据模型 
const { address } = require('../model/db')
//===============API写下面================================================ 
//小程序端 获取地址列表 
router.get('/wxAddress', async (req, res) => {
    try {
        const addressList = await address.find({
            openid: req.query.openid
        });
        res.send({ message: 'success', result: addressList });
    } catch (err) {
        res.send({ message: 'fail', result: err })
    }
})
// 删除地址API
router.get('/wxDelAddress', async (req, res) => {
    try {
        const { _id } = req.query
        await address.findByIdAndDelete(_id)
        res.send('success')
    } catch (error) {
        console.log(error)
        res.send('fail')
    }

})
//小程序端 保存地址信息 
router.post('/wxAddressSave', async (req, res) => {
    try {
        //设置默认地址 
        const { openid, isDefault, _id } = req.body;
        if (isDefault) {
            //遍历数据库，将我的地址中isDefault设置为false
            await address.findOneAndUpdate({ openid, isDefault }, { isDefault: false });
        } if (_id) {
            //id存在，则修改地址信息 
            await address.findByIdAndUpdate(_id, req.body)
        } else {
            //id不存在，执行添加操作 
            await address.create(req.body);
        } res.send('success');
    } catch (err) {
        res.send('fail')
        console.log('add:' + err);
    }
})

//===============API写在上面============================================= 

//导出路由 
module.exports = router;